<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of accountcreate
 *
 * @author Dragon.hu add @2015.9.2
 */
defined('BASEPATH') or die('forbidden');

class Accountcreate_Controller extends Controller {

	private $inc;
	private $logdb;	//数据库连接
	private $m;	//数据库连接
	private $platformList;	//平台列表
	private $server_role_info;	//mongo角色

	function _init() {
		check_level(50, segment(0), segment(1), segment(2, 'index'));
		set_time_limit(0);
		
		$this->inc = $this->config['inc'];
		$this->platformList = $this->inc['platform_list'];
		//得到选择的区号
		$areanum = $_SESSION['area_selected_id'];
		if ($areanum == '')
		{
			echo "<script>alert('" . translate('C_SELECT_AREA_TEXT') . "');</script>";
			return;
		}

		//query server mapping
		//$selectSql = "SELECT * FROM server_mapping WHERE dbtype='6' ";
		//$this->db->query($selectSql);
		//$this->server_info=$this->db->get_array('default');
		//query server mapping
		$selectSql = "SELECT * FROM server_mapping WHERE dbtype='1' AND areanum = $areanum";
		//$selectSql = "SELECT * FROM server_mapping WHERE dbtype='1'";
		$this->db->query($selectSql);
		$this->server_role_info=$this->db->get_array('default');

		//db数据库
		$this->m = new MongoClient("mongodb://{$this->server_role_info['username']}:{$this->server_role_info['userpwd']}@{$this->server_role_info['dbip']}");
		// log数据库
		//$this->logdb = $this->load->database('log_db');

		//log数据库
		$this->logdb = getTmpDbConnect(PLATFORM_ALL, 'all', $areanum, DBTYPE_LOG);

		
		if (false == $this->logdb) {
			//内部有提示错误，在此就不提示了
			//echo "<script>alert(' connect areanum:$areanum error ');</script>";
			return;
		}
	}

	function index() {
	//游戏帐号
	// $collection=$this->m->{$this->server_role_info['dbname']}->PlayerSimple;
	// $consumer_all=$collection->find(array( 'createtime' =>array('$gte'=>strtotime('2017/12/13'),'$lt'=>strtotime('2017/12/14'))));
	// $consumer_ids=array_map('array_shift', iterator_to_array($consumer_all,false));
	// $consumers = count($consumer_ids);//注册数量
	// $consumer_ids='('.(array('1000200016271')?implode(',',(array('1000200016271')):0).')';
	// $date2=strtotime('+1 day',strtotime('2018/01/02'));
	// $sql2="SELECT playerid,COUNT(*) AS num FROM  gamelog_1  where DATE_FORMAT(FROM_UNIXTIME(time),'%Y %m %d') = DATE_FORMAT(FROM_UNIXTIME($date2),'%Y %m %d')    GROUP BY playerid  ";
	// $result2 = $this->logdb->count_log($sql2);
	// $retained2 = count($result2);
	// var_dump($retained2);
        echo "log_role/accountcreate/index" ;
		$this->view->display("log_role/accountcreate/index");
	}

	function flexigrid() {
		list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();

        $query=$_POST['query'];
	// if ($request->has('start_time') && $request->start_time != '' && $request->has('end_time') && $request->end_time != '') {
	//     $begin=new \DateTime($request->start_time);
	//     $end=new \DateTime($request->end_time);
	//     $end = $end->modify( '+1 day' );
	// }else
        if($query != '' ) {
            $begin=new \DateTime($query);
            $end=new \DateTime();
            $end = $end->modify('+1 day');
        }else{
            $begin=new \DateTime('-14 day');
            $end=new \DateTime();
            $end = $end->modify('+1 day');  // 不包含结束日期当天，需要人为的加一天
        }

        $interval = new \DateInterval('P1D');
        //$interval = \DateInterval::createFromDateString('1 day');  // 等同于上一条
        // 如果第4个参数为\DatePeriod::EXCLUDE_START_DATE，则不包含开始日期当天
        $daterange = new \DatePeriod($begin, $interval ,$end);

        //游戏角色
        $collection=$this->m->{$this->server_role_info['dbname']}->PlayerSimple;
        //$stime=microtime(true);
        $this->logdb->select_db();
        //$etime=microtime(true);
        //$total=$etime-$stime;   //计算差值
        //log_message($total,'info');
        $rows=array();
        foreach($daterange as $key => $date){
            $date_str=$date->format("Y/m/d");
            $consumer_all=$collection->find(array( 'createtime' =>array('$gte'=>strtotime($date_str),'$lt'=>strtotime('+1 day',strtotime($date_str)))));
            $consumer_accounts=array_map('array_shift', iterator_to_array($consumer_all,false));
            $consumers=count($consumer_accounts);                                        //注册数量
            $consumer_ids='('.($consumer_accounts?implode(',',$consumer_accounts):0).')';

            //注册日期
            $n['regdate']=$date_str;
            //每天的注册用户数
            $regcount[] = $consumers;
            $n['regcount']=$consumers;

            //次日留存
            $date2=strtotime('+1 day',strtotime($date_str));
            $sql2="SELECT playerid,COUNT(*) AS num FROM  gamelog_1  where DATE_FORMAT(FROM_UNIXTIME(time),'%Y-%m-%d') = DATE_FORMAT(FROM_UNIXTIME($date2),'%Y-%m-%d') AND playerid IN {$consumer_ids} GROUP BY playerid  ";

            $result2 = $this->logdb->count_log($sql2);
            $retained2 = count($result2);
            $n['retaineds2'] = $retained2;

            //次日留存率
            $n['retainedsr2'] = $retained2?round(($retained2 / $consumers) * 100):0;

            //7日留存
            $date7=strtotime('+6 day',strtotime($date_str));
            $sql7="SELECT playerid, COUNT(*) AS num FROM gamelog_1  where DATE_FORMAT(FROM_UNIXTIME(time),'%Y-%m-%d') = DATE_FORMAT(FROM_UNIXTIME($date7),'%Y-%m-%d') AND playerid IN {$consumer_ids} GROUP BY playerid";
            $result7 = $this->logdb->count_log($sql7);
            $retained7 = count($result7);
            $n['retaineds7'] = $retained7;
            //7日留存率
            $n['retainedsr7'] = $retained7?round(($retained7 / $consumers) * 100):0;

            //30日留存
            $date30=strtotime('+29 day',strtotime($date_str));
            $sql30="SELECT playerid, COUNT(*) AS num FROM gamelog_1  where DATE_FORMAT(FROM_UNIXTIME(time),'%Y-%m-%d') = DATE_FORMAT(FROM_UNIXTIME($date30),'%Y-%m-%d') AND playerid IN {$consumer_ids} GROUP BY playerid";
            $result30 = $this->logdb->count_log($sql30);
            $retained30 = count($result30);
            $n['retaineds30'] = $retained30;
            //30日留存率
            $n['retainedsr30'] = $retained30?round(($retained30 / $consumers) * 100):0;

            //60日留存a

            $date60=strtotime('+59 day',strtotime($date_str));
            $sql60="SELECT playerid, COUNT(*) AS num FROM gamelog_1  where DATE_FORMAT(FROM_UNIXTIME(time),'%Y-%m-%d') = DATE_FORMAT(FROM_UNIXTIME($date60),'%Y-%m-%d') AND playerid IN {$consumer_ids} GROUP BY playerid";
            $result60 = $this->logdb->count_log($sql60);
            $retained60 = count($result60);
            $n['retaineds60'] = $retained60;
            //60日留存率
            $n['retainedsr60']= $retained60?round(($retained60 / $consumers) * 100):0;

            $rows[] = array('id' => $key, 'cell' => $n);
        }

		
		$result = array(
	            'page' => $page,
	            'total' => count($daterange),
	            'rows' => $rows
		);
		
		echo json_encode($result);
	}


//    public function showRetained(Request $request)
//    {
//        if ($request->has('start_time') && $request->start_time != '' && $request->has('end_time') && $request->end_time != '') {
//            $begin=new \DateTime($request->start_time);
//            $end=new \DateTime($request->end_time);
//            $end = $end->modify( '+1 day' );
//        }elseif($request->start_time != '' and $request->end_time == '') {
//            $begin=new \DateTime($request->start_time);
//            $end=new \DateTime();
//            $end = $end->modify( '+1 day' );
//        }else {
//            $begin=new \DateTime('-59 day');
//            $end=new \DateTime();
//            $end = $end->modify( '+1 day' );  // 不包含结束日期当天，需要人为的加一天
//        }
//
//
//        $interval = new \DateInterval('P1D');
//        //$interval = \DateInterval::createFromDateString('1 day');  // 等同于上一条
//        // 如果第4个参数为\DatePeriod::EXCLUDE_START_DATE，则不包含开始日期当天
//        $daterange = new \DatePeriod($begin, $interval ,$end);
//        $regdate=$regcount=$retaineds2=$retaineds7=$retaineds30=$retaineds60=$retainedsr2=$retainedsr7=$retainedsr30=$retainedsr60=[];
//        foreach($daterange as $key => $date){
//            $data = Consumer::whereDate('created_at', $date->format("Ymd"))->select('id')->get();
//            $consumer_ids = $data->pluck('id');//注册ID
//            $consumers = $data->count();//注册数量
//            //注册日期
//            $regdate[]=$date->format("Y/m/d");
//            //每天的注册用户数
//            $regcount[] = $consumers;
//            //次日留存
//            $retained2 = Logrecord::whereDate('created_at', $date->format("Ymd")+1)
//                ->whereIn('consumer_id', $consumer_ids)->groupBy('consumer_id')->get()->count();
//            $retaineds2[] = $retained2;
//            //次日留存率
//            $retainedsr2[] = $retained2?round(($retained2 / $consumers) * 100):0;
//            //7日留存
//            $retained7 = Logrecord::whereDate('created_at', $date->format("Ymd")+6)
//                ->whereIn('consumer_id', $consumer_ids)->groupBy('consumer_id')->get()->count();
//            $retaineds7[] = $retained7;
//            //7日留存率
//            $retainedsr7[] = $retained7?round(($retained7 / $consumers) * 100):0;
//            //30日留存
//            $retained30 = Logrecord::whereDate('created_at', $date->format("Ymd")+29)
//                ->whereIn('consumer_id', $consumer_ids)->groupBy('consumer_id')->get()->count();
//            $retaineds30[] = $retained30;
//            //30日留存率
//            $retainedsr30[] = $retained30?round(($retained30 / $consumers) * 100):0;
//            //60日留存
//            $retained60 = Logrecord::whereDate('created_at', $date->format("Ymd")+59)
//                ->whereIn('consumer_id', $consumer_ids)->groupBy('consumer_id')->get()->count();
//            $retaineds60[] = $retained60;
//            //60日留存率
//            $retainedsr60[] = $retained60?round(($retained60 / $consumers) * 100):0;
//        }
//        $retains=[
//            'regdate'=>$regdate,
//            'regcount'=>$regcount,
//            'retaineds2'=>$retaineds2,
//            'retaineds7'=>$retaineds7,
//            'retaineds30'=>$retaineds30,
//            'retaineds60'=>$retaineds60,
//            'retainedsr2'=>$retainedsr2,
//            'retainedsr7'=>$retainedsr7,
//            'retainedsr30'=>$retainedsr30,
//            'retainedsr60'=>$retainedsr60,
//        ];
//        return $retains;
//    }


}
